<template>
  <div class="add-students-page">
    <div class="page-header">
      <h1>📚 批量添加学生账号</h1>
      <p class="subtitle">通过上传表格快速批量添加学生账号</p>
    </div>

    <div class="content-container">
      <!-- 上传文件区域 -->
      <div class="upload-section">
        <div class="section-card">
          <div class="card-header">
            <h2>📁 上传学生信息表格</h2>
            <span class="tip">支持 Excel (.xlsx, .xls) 和 CSV 文件</span>
          </div>
          
          <div class="upload-area" 
               @drop.prevent="handleFileDrop" 
               @dragover.prevent="handleDragOver"
               @dragleave.prevent="handleDragLeave"
               :class="{ 'drag-over': isDragging }">
            <input 
              type="file" 
              ref="fileInput" 
              @change="handleFileSelect" 
              accept=".xlsx,.xls,.csv"
              style="display: none;"
            />
            
            <div class="upload-icon">📄</div>
            <div class="upload-text">
              <p class="primary-text">拖拽文件到此处，或</p>
              <button class="select-file-btn" @click="triggerFileSelect">选择文件</button>
            </div>
            
            <div class="file-info" v-if="selectedFile">
              <span class="file-name">📎 {{ selectedFile.name }}</span>
              <button class="remove-btn" @click="removeFile">✕</button>
            </div>
          </div>

          <div class="format-guide">
            <h3>📋 表格格式说明</h3>
            <div class="guide-content">
              <p>表格应包含以下列（第一行为表头）：</p>
              <ul>
                <li><strong>姓名</strong> - 学生姓名（必填）</li>
                <li><strong>账号</strong> - 登录账号（必填，建议使用学号）</li>
              </ul>
              <button class="download-template-btn" @click="downloadTemplate">
                ⬇️ 下载模板文件
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部：操作按钮 -->
    <div class="action-section">
      <div class="action-buttons">
        <button class="btn btn-secondary" @click="handleReset">
          🔄 重置
        </button>
        <button 
          class="btn btn-primary" 
          @click="handleSubmit"
          :disabled="parsedStudents.length === 0 || isSubmitting"
        >
          <span v-if="!isSubmitting">✅ 提交添加 ({{ parsedStudents.length }})</span>
          <span v-else>⏳ 处理中...</span>
        </button>
      </div>
    </div>

    <!-- 结果提示框 -->
    <div class="result-modal" v-if="showResult" @click="closeResult">
      <div class="result-content" @click.stop>
        <div class="result-header" :class="resultType">
          <span class="result-icon">{{ resultType === 'success' ? '✅' : '❌' }}</span>
          <h3>{{ resultType === 'success' ? '添加成功' : '添加失败' }}</h3>
        </div>
        <div class="result-body">
          <p>{{ resultMessage }}</p>
          <div v-if="resultDetails" class="result-details">
            <pre>{{ resultDetails }}</pre>
          </div>
        </div>
        <button class="btn btn-primary" @click="closeResult">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
import logger from '../utils/logger.js'

export default {
  name: 'AddStudents',
  data() {
    return {
      selectedFile: null,
      parsedStudents: [],
      isDragging: false,
      isSubmitting: false,
      showResult: false,
      resultType: 'success',
      resultMessage: '',
      resultDetails: null
    }
  },
  methods: {
    // 触发文件选择
    triggerFileSelect() {
      this.$refs.fileInput.click()
    },
    
    // 处理文件选择
    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.processFile(file)
      }
    },
    
    // 处理文件拖拽
    handleFileDrop(event) {
      this.isDragging = false
      const file = event.dataTransfer.files[0]
      if (file) {
        this.processFile(file)
      }
    },
    
    handleDragOver() {
      this.isDragging = true
    },
    
    handleDragLeave() {
      this.isDragging = false
    },
    
    // 处理文件
    async processFile(file) {
      const validTypes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel',
        'text/csv'
      ]
      
      if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls|csv)$/i)) {
        alert('❌ 请上传有效的Excel或CSV文件')
        return
      }
      
      this.selectedFile = file
      
      try {
        const data = await this.readFile(file)
        this.parseFileData(data, file.type)
      } catch (error) {
        logger.error('文件读取失败:', error)
        alert('❌ 文件读取失败，请重试')
      }
    },
    
    // 读取文件
    readFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => resolve(e.target.result)
        reader.onerror = reject
        reader.readAsBinaryString(file)
      })
    },
    
    // 解析文件数据
    parseFileData(data, fileType) {
      try {
        const workbook = XLSX.read(data, { type: 'binary' })
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 })
        
        // 跳过表头，解析数据
        const students = []
        for (let i = 1; i < jsonData.length; i++) {
          const row = jsonData[i]
          if (row.length > 0 && row[0]) {
            students.push({
              name: row[0] || '',
              account: row[1] || ''
            })
          }
        }
        
        this.parsedStudents = students
        logger.log('解析到学生数据:', students)
      } catch (error) {
        logger.error('文件解析失败:', error)
        alert('❌ 文件格式不正确，请检查后重试')
      }
    },
    
    // 移除文件
    removeFile() {
      this.selectedFile = null
      this.parsedStudents = []
      this.$refs.fileInput.value = ''
    },
    
    // 下载模板
    downloadTemplate() {
      const template = [
        ['姓名', '账号'],
        ['张三', '20240001'],
        ['李四', '20240002'],
        ['王五', '20240003']
      ]
      
      const ws = XLSX.utils.aoa_to_sheet(template)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '学生账户信息')
      XLSX.writeFile(wb, '学生账号导入模板.xlsx')
    },
    
    // 重置
    handleReset() {
      if (confirm('确定要重置所有数据吗？')) {
        this.selectedFile = null
        this.parsedStudents = []
        if (this.$refs.fileInput) {
          this.$refs.fileInput.value = ''
        }
      }
    },
    
    // 提交
    async handleSubmit() {
      // 检查是否选择了文件
      if (!this.selectedFile) {
        alert('❌ 请先选择要上传的Excel文件')
        return
      }
      
      // 验证数据预览
      if (this.parsedStudents.length === 0) {
        alert('❌ 文件中没有找到有效的学生数据，请检查文件格式')
        return
      }
      
      // 验证数据完整性
      const invalidStudents = this.parsedStudents.filter(s => !s.name || !s.account)
      if (invalidStudents.length > 0) {
        alert(`❌ 发现 ${invalidStudents.length} 条数据不完整（缺少姓名或账号），请检查后重试`)
        return
      }
      
      this.isSubmitting = true
      
      try {
        logger.log('📤 准备上传Excel文件:', this.selectedFile.name)
        logger.log('📊 预计导入学生数量:', this.parsedStudents.length)
        
        // 创建FormData对象
        const formData = new FormData()
        formData.append('file', this.selectedFile)
        
        logger.log('🌐 [API] 调用Excel导入接口')
        logger.log('🔗 [API] 接口地址: /goc/excel/import')
        
        // 导入axios实例
        const api = (await import('@/api/config.js')).default
        
        // 调用文件上传接口
        const response = await api.post('/goc/excel/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          timeout: 30000  // 30秒超时
        })
        
        logger.log('✅ Excel导入成功:', response)
        
        // 成功
        this.showResultModal('success', `✅ 成功导入 ${this.parsedStudents.length} 个学生账号！`)
        
        // 重置表单
        setTimeout(() => {
          this.handleReset()
        }, 2000)
        
      } catch (error) {
        logger.error('❌ 上传失败:', error)
        logger.error('📊 错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })
        
        const errorMsg = error.response?.data?.message || error.message || '未知错误'
        this.showResultModal('error', '❌ 导入失败，请重试', errorMsg)
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 显示结果弹窗
    showResultModal(type, message, details = null) {
      this.resultType = type
      this.resultMessage = message
      this.resultDetails = details
      this.showResult = true
    },
    
    // 关闭结果弹窗
    closeResult() {
      this.showResult = false
      this.resultDetails = null
    }
  }
}
</script>

<style scoped>
.add-students-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 20px;
}

.page-header {
  text-align: center;
  color: white;
  margin-bottom: 40px;
}

.page-header h1 {
  font-size: 36px;
  margin-bottom: 10px;
  font-weight: 700;
}

.subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.content-container {
  max-width: 800px;
  margin: 0 auto;
}

.section-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.card-header {
  margin-bottom: 20px;
}

.card-header h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 8px;
}

.tip {
  font-size: 13px;
  color: #999;
}

/* 上传区域 */
.upload-area {
  border: 3px dashed #ddd;
  border-radius: 12px;
  padding: 40px 20px;
  text-align: center;
  transition: all 0.3s;
  cursor: pointer;
  background: #fafafa;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #667eea;
  background: #f0f4ff;
}

.upload-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.upload-text .primary-text {
  color: #666;
  margin-bottom: 15px;
}

.select-file-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.3s;
}

.select-file-btn:hover {
  background: #5568d3;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.file-info {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 12px 20px;
  background: #e8f5e9;
  border-radius: 8px;
}

.file-name {
  color: #2e7d32;
  font-weight: 500;
}

.remove-btn {
  background: #f44336;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 格式说明 */
.format-guide {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.format-guide h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.guide-content p {
  color: #666;
  margin-bottom: 10px;
}

.guide-content ul {
  list-style: none;
  padding: 0;
  margin: 15px 0;
}

.guide-content li {
  padding: 8px 0;
  color: #555;
  border-bottom: 1px solid #eee;
}

.guide-content li:last-child {
  border-bottom: none;
}

.download-template-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  margin-top: 15px;
  transition: all 0.3s;
}

.download-template-btn:hover {
  background: #45a049;
  transform: translateY(-2px);
}

/* 操作按钮 */
.action-section {
  max-width: 1400px;
  margin: 30px auto 0;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.btn {
  padding: 14px 40px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background: #4CAF50;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background: white;
  color: #666;
  border: 2px solid #ddd;
}

.btn-secondary:hover {
  background: #f8f9fa;
  border-color: #999;
}

/* 结果弹窗 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.result-content {
  background: white;
  border-radius: 16px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.result-header {
  text-align: center;
  margin-bottom: 20px;
}

.result-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 15px;
}

.result-header h3 {
  font-size: 24px;
  color: #333;
}

.result-header.success h3 {
  color: #4CAF50;
}

.result-header.error h3 {
  color: #f44336;
}

.result-body {
  text-align: center;
  margin-bottom: 20px;
}

.result-body p {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.result-details {
  text-align: left;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.result-details pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 13px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 28px;
  }
  
  .section-card {
    padding: 20px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style> 